﻿using System;
using Sushi.Core;


namespace Sushi.Core
{
   ///<summary>
   /// Returns report results from UsageReportRepository while checking AuthorizationAuthority for access
   ///</summary>
   public class SushiComponent 
   {
      ///<summary>
      /// Initializes a new instance of the <see cref="SushiComponent"/> class.
      ///</summary>
      ///<param name="reportRepository">
      /// The <see cref="IUsageReportRepository"/> instance to use for Counter usage data retrieval.
      /// </param>
      ///<param name="authorizationAuthority">
      /// The <see cref="IAuthorizationAuthority"/> instance to use for requestor / customer authorization.
      ///</param>
      public SushiComponent(IUsageReportRepository reportRepository, IAuthorizationAuthority authorizationAuthority)
      {
         ReportRepository = reportRepository;
         AuthorizationAuthority = authorizationAuthority;
      }

      /// <summary>
      /// Gets the <see cref="IUsageReportRepository"/> instance that was injected when this instance was created.
      /// </summary>
      public IUsageReportRepository ReportRepository { get; private set; }

      /// <summary>
      /// Gets the <see cref="IAuthorizationAuthority"/> instance that was injected when this instance was created.
      /// </summary>
      public IAuthorizationAuthority AuthorizationAuthority { get; private set; }

      /// <summary>
      /// Retrieves an instance of the <see cref="Reports"/> class containing the requested usage statistics.
      /// </summary>
      /// <param name="request">The request object from the webservice.</param>
      /// <returns>An instance of the <see cref="Reports"/> class containing the requested usage statistics.</returns>
      public Report[] GetSushiReports(ReportRequest request)
      {
			bool authorized = AuthorizationAuthority.IsRequestorAuthorized(request.Requestor, request.CustomerReference);

         if (!authorized)
         {
				throw new SushiServiceException("Requestor is not authorized to view usage for this customer.");
         }

			Customer customer = GetCustomerFromReference(request.CustomerReference);
			DateRange range = GetDateRangeFromRange(request.ReportDefinition.Filters.UsageDateRange);


			return ReportRepository.GetUsageReports(request);
      }

      #region Sushi-to-Counter converters
      private static Customer GetCustomerFromReference(CustomerReference reference)
      {
         return new Customer
                   {
                      ID = reference.ID,
                      Name = reference.Name
                   };
      }

      private static DateRange GetDateRangeFromRange(Range range)
      {
         return new DateRange
                   {
                      Begin = range.Begin,
                      End = range.End
                   };
      }
      #endregion
   }
}